package com.zealfi.example.test.rabbitmq.base;

import com.rabbitmq.client.Channel;
import com.zealfi.example.test.rabbitmq.util.FastJsonMQMessageConvert;
import com.zealfi.example.test.rabbitmq.util.JsonTool;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.support.converter.MessageConversionException;

/**
 * @功能:【BaseConsumer 消费者基类】
 * @作者:代守诚
 * @日期:2018/10/22
 * @时间:15:46
 */
public abstract class BaseConsumer implements ChannelAwareMessageListener {

    private FastJsonMQMessageConvert convert = new FastJsonMQMessageConvert();

    protected <T> T fromMessage(Message message, Class<T> cls) throws MessageConversionException {
        return JsonTool.getObj(String.valueOf(convert.fromMessage(message)), cls);
    }

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        try {
            processMessage(message);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            System.err.println("********处理异常:" + JsonTool.getString(message));
            System.err.println("*********" + e);
            processExceptionMessage(message, channel);
        }
    }

    protected abstract void processExceptionMessage(Message message, Channel channel) throws Exception;

    protected abstract void processMessage(Message message);

}
